package com.NetSunWeiQin.chapter05.httpserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class HttpServer {
    private Selector selector = null;
    private ServerSocketChannel serverSocketChannel = null;
    private int port = 8848;
    private Charset charset = StandardCharsets.UTF_8;

    public HttpServer() {
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().setReuseAddress(true);
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(port));
            System.out.println("INFO  服务器启动   " + "http://localhost:" + port     );
        } catch (Exception e) {
            System.out.println("ERROR  " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void service() throws IOException {
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler());
        for (; ; ) {
            int n = selector.select();

            if (n == 0) continue;
            Set readyKeys = selector.selectedKeys();
            Iterator it = readyKeys.iterator();
            while (it.hasNext()) {
                SelectionKey key = null;
                try {
                    key = (SelectionKey) it.next();
                    it.remove();
                    final Handler handler = (Handler) key.attachment();
                    handler.handle(key);
                } catch (IOException e) {
                    e.printStackTrace();
                    try {
                        key.cancel();
                        key.channel().close();
                    } catch (Exception ex) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    public static void main(String args[]) {
        final HttpServer server = new HttpServer();
        try {
            server.service();
        } catch (Exception e) {
            System.out.println("ERROR  " + e.getMessage());
        }
    }
}


